/*
   Copyright (c) 2023 李伟国
   learner-platform is licensed under Mulan PSL v2.
   You can use this software according to the terms and conditions of the Mulan PSL v2.
   You may obtain a copy of Mulan PSL v2 at:
               http://license.coscl.org.cn/MulanPSL2
   THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.  
   See the Mulan PSL v2 for more details. 
*/

package cn.platform.page;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 获取请求，拿到分页的参数，创建分页类
 */
public class PageFactory {
    public static Page defaultPage(){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes == null? null: requestAttributes.getRequest();

        int size = 20;
        int current = 1;

        //每页多少条数据
        String limitString = request.getParameter("size");
        if (!ObjectUtils.isEmpty(limitString)) {
            size = Integer.parseInt(limitString);
        }

        //第几页
        String pageString = request.getParameter("current");
        if (!ObjectUtils.isEmpty(pageString)) {
            current = Integer.parseInt(pageString);
        }
        Page defaultPage = new Page(current, size);
        //是否排序
        String order = request.getParameter("order");
        String field = request.getParameter("field");
        if (!ObjectUtils.isEmpty(order) && !ObjectUtils.isEmpty(field)) {
            if ("asc".equals(order)) {
                defaultPage.addOrder(OrderItem.asc(field));
            }else {
                defaultPage.addOrder(OrderItem.desc(field));
            }
        }
        return defaultPage;
    }
}
